﻿using B.S.GridManage.Api.Read.Application.Command.GridTeam;
using B.S.GridManage.Api.Read.Dtos;
using B.S.GridManage.Api.Read.Extension;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using System.Collections.Generic;

namespace B.S.GridManage.Api.Read.Application.Handler.GridTeam
{
    /// <summary>
    /// 查询网格队伍的处理类-中介者
    /// </summary>
    public class GetGridTeamHandler : IRequestHandler<GetGridTeamCommand, ApiResult<List<GridTeamDto>>>
    {
        private readonly IBaseRepository<GridTeamModel> teamRepo;
        private readonly IBaseRepository<AreaModel> areaRepo;
        private readonly IBaseRepository<PhysicallGridModel> gridRepo;

        public GetGridTeamHandler(IBaseRepository<GridTeamModel> teamRepo, IBaseRepository<AreaModel> areaRepo, IBaseRepository<PhysicallGridModel> gridRepo)
        {
            this.teamRepo = teamRepo;
            this.areaRepo = areaRepo;
            this.gridRepo = gridRepo;
        }
        /// <summary>
        ///  查询网格队伍的处理方法-中介者
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>响应包装类</returns>
        
        public async Task<ApiResult<List<GridTeamDto>>> Handle(GetGridTeamCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<GridTeamDto>> res = new ApiResult<List<GridTeamDto>>();

            //表达式
            var teams = teamRepo.GetAll().Where(x=>x.IsDeleted==false);
            var areas = areaRepo.GetAll().Where(x => x.IsDeleted == false);
            var grids = gridRepo.GetAll().Where(x => x.IsDeleted == false);

            //条件判断
            if (request.AreaName.IsNotNull()) {
                areas = areas.Where(x => x.AreaName.Contains(request.AreaName));
            }

            if (request.GridName.IsNotNull())
            {
                grids = grids.Where(x => x.GridName.Contains(request.GridName));
            }



            var linq = from t in teams
                       join a in areas on t.AreaId equals a.Id
                       join g in grids on t.GridId equals g.Id
                       select new GridTeamDto() {                        
                        Id = t.Id,
                         AreaId = t.AreaId,
                          GridId = t.GridId,
                           AreaName=a.AreaName,
                            GriddeeStrs= t.GriddeeStrs,
                             Grider= t.Grider,
                              GridName = g.GridName,
                           
                       };

            res.Data = linq.ToList();
            res.Msg = "查询网格队伍列表成功!";
            res.Code = ApiEnum.Success;

            return res;
        }
    }
}
